<?php
/**
 * Created by PhpStorm.
 * User: jack.shan
 * Date: 2020/9/15
 * Time: 16:33
 */
namespace app\index\controller;

use app\index\BaseController;
use app\model\User;
use app\validate\UserLo;
use app\validate\Userv;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\View;

class Test extends BaseController
{

    public function index()
    {
        $as = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        foreach ($as as $a)
        {
            if($this->checknum($a))
            {
                echo $a . "<br />";
            }
        }
        return;
    }

    protected function checknum($num)
    {
        if($num % 2 == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }


    public function index2()
    {
        $a = ['I', 'am', 'jack'];

        $as = implode('', $a);

        return $as;
    }

    //增加
    public function add()
    {
        if($this->request->isPost())
        {

            $name = $this->request->param("name");
            $password = $this->request->param("password");
            $email = $this->request->param("email");


            validate(Userv::class)->check([
                'username'  => $name,
                'password' => $password,
                'email' => $email,
            ]);

            //1、通过框架的orm特性 增加数据记录
            $user = new User();
            $user->username = $name;
            $user->password = $password;
            $user->email = $email;
            $user->fans = 1;

            $user->save();

            $id = $user->id;

            $file = $this->request->file('logo');

            if($file){

                $picadr = Filesystem::disk('data')->putFile( 'topic', $file, function() use($id){
                    return date('Ymd') . '/' . intval($id / 1000) .  '/' . time();
                });
                $user->logo = $picadr;

                $user->save();
            }

            return redirect("show?id=" . $id);
        }

        return View::fetch("add");
    }

    //查询
    public function show()
    {
        $id = $this->request->param("id");

        //$user = User::where("id", $id)->find()->toArray();
        $user = User::find($id);

        View::assign([
            'user' => $user->toArray()
        ]);

        return View::fetch("show");
    }

    //修改
    public function edit()
    {
        $id = $this->request->param('id');

        $user = User::where("id", $id)->find();

        $user->fans = 1000;
        $r = $user->save();


        if($r)
        {
            return "用户数据修改成功";
        }
        else
        {
            return "用户数据修改失败";
        }
    }

    //修改
    public function del()
    {
        $id = $this->request->param('id');

        $user = User::where("id", $id)->find();

        $r = $user->delete();


        if($r)
        {
            return "用户数据删除成功";
        }
        else
        {
            return "用户数据删除失败";
        }
    }



}